"use client"

import type React from "react"

import { useState } from "react"
import { CopyOutlined, EditOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons"
import { message, Popconfirm, Card, Typography, Button, Tooltip } from "antd"
import type { Module, HostsBlock } from "../types"

const { Text } = Typography

interface ModuleCardProps {
  module: Module
  hostsBlock?: HostsBlock
  onEdit: (module: Module) => void
  onDelete: (id: string) => void
  onCopy?: (content: string) => void
  onClick?: () => void
}

const ModuleCard = ({ module, hostsBlock, onEdit, onDelete, onCopy }: ModuleCardProps) => {
  const [isDeleting, setIsDeleting] = useState(false)

  const handleCopy = (e: React.MouseEvent) => {
    e.stopPropagation()
    if (hostsBlock && onCopy) {
      onCopy(hostsBlock.content)
      message.success("已复制到剪贴板")
    }
  }

  const handleEdit = (e: React.MouseEvent) => {
    e.stopPropagation()
    onEdit(module)
  }

  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation()
    if (isDeleting) return
    setIsDeleting(true)

    try {
      onDelete(module.id)
      message.success("删除成功")
    } catch (error) {
      message.error("删除失败")
    } finally {
      setIsDeleting(false)
    }
  }

  // 格式化 hosts 内容，只显示前几行
  const formatHostsContent = () => {
    if (!hostsBlock) return null

    const lines = hostsBlock.content.split("\n").slice(0, 4)
    return lines.map((line, index) => {
      const trimmedLine = line.trim()
      if (trimmedLine.startsWith("#")) {
        return (
          <div key={index} style={{ color: "var(--gray-500)", fontFamily: "monospace", fontSize: "11px" }}>
            {line}
          </div>
        )
      }
      return (
        <div key={index} style={{ fontFamily: "monospace", fontSize: "11px" }}>
          {line}
        </div>
      )
    })
  }

  // Generate a consistent color based on module name
  const getModuleColor = () => {
    const hash = module.name.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0)
    const hue = hash % 360
    return `hsl(${hue}, 70%, 65%)`
  }

  // Get first letter of module name
  const getModuleInitial = () => {
    return module.name.charAt(0).toUpperCase()
  }

  return (
    <Card
      bordered={false}
      className="module-card"
      size="small"
      bodyStyle={{ padding: 0 }}
      style={{
        boxShadow: "0 1px 2px rgba(0, 0, 0, 0.03)",
        transition: "all 0.3s ease",
        border: "1px solid #f1f5f9",
        borderRadius: "12px",
        overflow: "hidden",
      }}
      title={
        <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
          <div
            style={{
              width: "28px",
              height: "28px",
              borderRadius: "6px",
              background: `linear-gradient(135deg, ${getModuleColor()} 0%, ${getModuleColor()}80 100%)`,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              color: "white",
              fontSize: "14px",
              fontWeight: "bold",
            }}
          >
            {getModuleInitial()}
          </div>
          <div
            style={{
              fontWeight: 500,
              fontSize: "14px",
              whiteSpace: "nowrap",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}
          >
            {module.name}
          </div>
        </div>
      }
      extra={
        <Text type="secondary" style={{ fontSize: "12px" }}>
          {new Date(module.createdAt).toLocaleDateString()}
        </Text>
      }
    >
      <div style={{ padding: "0 12px 12px" }}>
        {module.description && (
          <div
            style={{
              fontSize: "12px",
              color: "var(--gray-600)",
              marginBottom: "8px",
              overflow: "hidden",
              textOverflow: "ellipsis",
              display: "-webkit-box",
              WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical",
            }}
          >
            {module.description}
          </div>
        )}

        {hostsBlock ? (
          <div style={{ marginBottom: "8px" }}>
            <div
              style={{
                backgroundColor: "var(--gray-50)",
                padding: "6px",
                borderRadius: "4px",
                position: "relative",
                overflow: "hidden",
              }}
            >
              {formatHostsContent()}
              <div
                style={{
                  position: "absolute",
                  bottom: 0,
                  left: 0,
                  right: 0,
                  height: "16px",
                  background: "linear-gradient(to bottom, transparent, var(--gray-50))",
                }}
              />
            </div>
          </div>
        ) : (
          <div
            style={{
              backgroundColor: "var(--gray-50)",
              padding: "6px",
              borderRadius: "4px",
              textAlign: "center",
              color: "var(--gray-500)",
              fontSize: "12px",
              marginBottom: "8px",
            }}
          >
            暂无 Hosts 配置
          </div>
        )}

        <div style={{ display: "flex", gap: "8px" }}>
          <Button
            type="default"
            size="small"
            style={{ flex: 1, fontSize: "12px", height: "28px" }}
            icon={<PlusOutlined />}
          >
            添加配置
          </Button>
          <Tooltip title="编辑模块">
            <Button
              type="text"
              size="small"
              style={{ width: "28px", height: "28px", padding: 0 }}
              icon={<EditOutlined />}
              onClick={handleEdit}
            />
          </Tooltip>

          {hostsBlock && (
            <Tooltip title="复制 Hosts 内容">
              <Button
                type="text"
                size="small"
                style={{ width: "28px", height: "28px", padding: 0 }}
                icon={<CopyOutlined />}
                onClick={handleCopy}
              />
            </Tooltip>
          )}

          <Tooltip title="删除模块">
            <Popconfirm
              title="确定要删除此模块吗？"
              onConfirm={handleDelete}
              okText="确定"
              cancelText="取消"
              onCancel={(e) => e?.stopPropagation()}
            >
              <Button
                type="text"
                danger
                size="small"
                style={{ width: "28px", height: "28px", padding: 0 }}
                icon={<DeleteOutlined />}
                onClick={(e) => e.stopPropagation()}
              />
            </Popconfirm>
          </Tooltip>
        </div>
      </div>
    </Card>
  )
}

export default ModuleCard
